package cn.shangtour.pic.service;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.UUID;
import javax.imageio.ImageIO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import cn.shangtour.common.utils.UploadUtil;
import cn.shangtour.common.vo.PicUploadResult;

@Service
public class PicService {
	@Value("${pic.pathDirPrefix}")
	public String pathDirPrefix;
	@Value("${pic.urlPrefix}")
	public String urlPreparePrefix;
	public PicUploadResult picUpload(MultipartFile pic) {
		PicUploadResult result=new PicUploadResult();
			String originName=pic.getOriginalFilename();
			String extName=
				originName.substring(originName.lastIndexOf("."));
			boolean satisfied=extName.matches(".(jpg|png|gif|JPG|PNG|GIF)$");
			if(!satisfied){
				result.setError(1);
				return result;
			}
			try{
				BufferedImage bufImage = ImageIO.read(pic.getInputStream());
				bufImage.getHeight();
				bufImage.getWidth();
			}catch(Exception e){
				result.setError(1);
				return result;}
			String dir="/"+UploadUtil.getUploadPath(originName, "upload")+"/";
			String pathDir=pathDirPrefix+dir;
			File file=new File(pathDir);
			if(!file.exists()){
				file.mkdirs();
			}
			String urlPrefix=urlPreparePrefix+dir;
			String fileName=UUID.randomUUID().toString()+extName;
			String filePath=pathDir+fileName;
			try{
				pic.transferTo(new File(filePath));
			}catch(Exception e){
				e.printStackTrace();
				result.setError(1);
				return result;
			}
			result.setUrl(urlPrefix+fileName);
		return result;
	}

	

}
